package com.suge.home.module.screen;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import sun.misc.BASE64Encoder;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.suge.common.constant.LoginConstants;
import com.suge.user.dao.dataobject.UserDO;
import com.suge.user.manager.UserManager;
import com.taobao.api.internal.util.codec.Base64;

public class Login {

	private static final Logger logger = LoggerFactory.getLogger(Login.class);

	@Autowired
    private HttpServletRequest request;
	@Autowired
	private UserManager userManager;
	
	public void execute(Context context, Navigator nav) {
		
//		String userName = (String) request.getSession().getAttribute(LoginConstants.ATTRIBUTE_USER_NAME);
//		
//		String userId = (String) request.getSession().getAttribute(LoginConstants.ATTRIBUTE_USER_ID_NUM);
//
//		if(userName!=null && userId!=null){
//			logger.error("Logined!");
//			nav.redirectToLocation("http://www.suge123.com/index.htm");
//			return;
//		}
//		
		String userId ="0";
		try{
		
			 String topParamsStr = request.getParameter("top_parameters");
			 String topSignStr = request.getParameter("top_sign");
			 String topSessionkeyStr = request.getParameter("top_session");
			 String topParams = URLDecoder.decode(topParamsStr, "UTF-8");
	         String topSign = URLDecoder.decode(topSignStr, "UTF-8");
	         String appSecret = "89fbda48de40e8833e8e0289919a4e06";
	         logger.error(topParamsStr+"----------"+topSignStr);
	         boolean success = verifyTopResponse(topParams, topSign, appSecret);
	         logger.error("Call back check is:"+success);
	         if (topSessionkeyStr!=null && !topSessionkeyStr.equals("")) {	 	
	        	 	logger.error("Login check success!");
	        	 	logger.error("Login check sessionKey!--:"+topSessionkeyStr);
//	                Map responseMap = convertBase64StringtoMap(topParams);
	        	 	UserDO userDO =  userManager.getTaoBaoUserInfo(topSessionkeyStr);
	        	 	request.getSession().setAttribute(LoginConstants.ATTRIBUTE_USER_NAME, userDO.getUserNick());	        
	        	 	request.getSession().setAttribute(LoginConstants.ATTRIBUTE_USER_ID_NUM, userDO.getUserId());
	        	 	request.getSession().setAttribute(LoginConstants.ATTRIBUTE_USE_IS_LOGIN, true);      	 
	         }
	         else{
	        	 logger.error("Md5 check failed nnd!");
	         }
		}
		catch(Exception e){
			logger.error(e.toString());
		}
		if(userId!=null){
			UserDO userDO = userManager.getAppUserByUserId(Long.parseLong(userId));
			context.put("userDO", userDO);
			nav.redirectToLocation("http://www.suge123.com/index.htm");
			return;
		}
		
		
	}
	
	  /**
     *
     * @param topParams TOP˽�в���δ��BASE64���ܣ�
     * @param topSign TOP�ص�ǩ��
     * @param appSecret Ӧ����Կ
     * @return ��֤�ɹ�����true�����򷵻�false
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static boolean verifyTopResponse(String topParams, String topSign, String appSecret)
                  throws NoSuchAlgorithmException, IOException {
           StringBuilder result = new StringBuilder();
           MessageDigest md5 = MessageDigest.getInstance("MD5");
           result.append(topParams).append(appSecret);
           byte[] bytes = md5.digest(result.toString().getBytes("UTF-8"));
           BASE64Encoder encoder = new BASE64Encoder();
           return encoder.encode(bytes).equals(topSign);
    }

    /**
     * �Ѿ���BASE64������ַ�ת��ΪMap����
     *
     * @param str
     * @return
     * @throws Exception
     */
    private static Map<String, String> convertBase64StringtoMap(String str) {
           if (str == null)
                  return null;
           String keyvalues = null;
           try {
                  keyvalues = new String(Base64.decodeBase64(URLDecoder.decode(str, "UTF-8").getBytes("UTF-8")));
           } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
           }
           String[] keyvalueArray = keyvalues.split("\\&");
           Map<String, String> map = new HashMap<String, String>();
           for (String keyvalue : keyvalueArray) {
                  String[] s = keyvalue.split("\\=");
                  if (s == null || s.length != 2)
                         return null;
                  map.put(s[0], s[1]);
           }
           return map;
    }


	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}


	public HttpServletRequest getRequest() {
		return request;
	}


	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}


	public UserManager getUserManager() {
		return userManager;
	}


}
